<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="程序号">
              <a-select popup-container="html" class="bacClass" :style="{ width: '200px' }"
                        v-model="pageData.programNumber" @focus="focusSel"
                        @search="handleSearch" @change="cxChange(pageData.programNumber)" :loading1="loading"
                        :filter-option="false" allow-search allow-clear>
                <a-option v-for="item in pageData.cxNameList" :value="item.id">
                  {{ item.programNumber }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="程序名称" field="programName">
              <a-input :style="{ width: '200px' }" v-model="pageData.programName" disabled>
                {{ pageData.programName }}
              </a-input>
            </a-form-item>
            <a-form-item label="程序类型" field="programType">
              <a-input :style="{ width: '200px' }" v-model="pageData.programType" disabled>
                {{ pageData.programType }}
              </a-input>
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar style="float: right" :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler"
                   @select="selectHandler" @export="exports" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressDragLeaveHidesColumns="true"
                         :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady"
                         style="height: 100%"
                         :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList"
                         :columnDefs="tc"
                         :localeText="localeText1" @columnResized="onColumnResized"
                         @columnMoved="onColumnMoved"></AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys :page-size-options="pagingList1" :page-size="pagination.pageSize" :total="total" show-total
                     show-jumper show-page-size @change="PageSize"
                     @page-size-change="change1" style="justify-content: center"/>

    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :mask-closable="false" :width="400"
              popup-container=".arco-tabs-content" height="100%" :visible="pageData.showAdd"
              :ok-loading="pageData.pageLoading"
              placement="bottom" unmountOnClose @ok="sideOk" @cancel="sideNo">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <a-tabs   :lazy-load="true">
        <a-form ref="formRef" layout="horizontal" :model="dataForm" size="small">
          <a-space>
            <a-form-item label-col-flex="80px" label="程序号" field="programNumber"
                         :validate-trigger="['change', 'blur']"
                         :rules="[{ required: true, message: '程序号必填' }]">
              <a-select popup-container="html" style="width: 200px" class="bacClass" v-model="dataForm.programNumber"
                        @focus="focusSel5"
                        @search="handleSearch5" @change="numChange" :loading5="loading5" allow-clear>
                <a-option v-for="item in pageData.NumberList" :value="item.programNumber">
                  {{ item.programNumber }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label-col-flex="80px" label="程序名称" field="programName"
                         :validate-trigger="['change', 'blur']"
                         :rules="[{ required: true, message: '程序名称必填' }]">
              <a-select popup-container="html" style="width: 200px" disabled v-model="dataForm.programName"
                        @focus="cxmcFocus2"
                        @change="cxChange2" allow-clear @click="cxClick2">
                <a-option v-for="item in pageData.cxNumberList" :value="item['programName']">
                  {{ item['programName'] }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label-col-flex="80px" label="程序类型" field="programType"
                         :rules="[{ required: true, message: '程序类型必填' }]" :validate-trigger="['change', 'blur']">
              <a-select popup-container="html" style="width: 200px" disabled v-model="dataForm.programType"
                        @focus="cxmcFocus2" allow-clear
                        @change="cxChange2" @click="cxClick2">
                <a-option v-for="item in pageData.cxNumberList" :value="item['programType']">
                  {{ item['programType'] }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-space>
        </a-form>
      </a-tabs>
      <a-space>
        <Toolbar :items="['添加工艺步骤', '删除', '复制']" @addSteps="addSteps" @del="delSteps"
                 @copy="copyPro"></Toolbar>
      </a-space>
      <a-table :style="{ marginTop: '10px' }" stripe :bordered="true" :scrollbar="true" sticky-header
               :columns="tableColumns1" :data="dataList" v-model:selected-keys="selectedRowKeys1" row-key="isTypeIds"
               :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }" size="mini" :pagination="false">
        <template #stepNo="{ record }">
          <a-input class="bacClass" v-model="record.stepNo"/>
        </template>
        <template #processingStep="{ record }">
          <a-select popup-container="html" class="bacClass" allow-search :loading1="loading1"
                    v-model="record.processingStep" @focus="focusSel1"
                    @search="handleSearch1">
            <a-option v-for="item of pageData.StepNameList" :value="item['technologyStep']">{{
                item['technologyStep']
              }}
            </a-option>
          </a-select>
        </template>
        <template #remark="{ record }">
          <a-input class="bacClass" placeholder=" " v-model="record.remark"/>
        </template>
      </a-table>
    </a-drawer>
    <a-modal v-model:visible="visible" title="选择程序号复制" :draggable="true">
      <a-form-item label="程序号" style="padding-left:17%">
        <a-select popup-container="html" class="bacClass" :style="{ width: '250px' }" v-model="dataForm.programId"
                  @focus="focusSel2"
                  @search="handleSearch2" @change="copyCode" :loading2="loading2" :filter-option="false" allow-search
                  allow-clear>
          <a-option v-for="item in pageData.cxIdList" :value="item.programName" :key="item.id">
            {{ item.programName }}
          </a-option>
        </a-select>
      </a-form-item>
      <template #footer>
        <a-button size="small" @click="visible.value = false">取消</a-button>
        <a-button type="primary" size="small" @click="handleSave">确认</a-button>
      </template>
    </a-modal>
    <a-modal v-model:visible="visible1" title="工艺步骤详情" :width="1200" :footer="false" :draggable="true">
      <a-table :style="{
        height: '100%',
        marginTop: '10px',
      }" stripe :bordered="true" :scrollbar="true" sticky-header :columns="tableColumns1" :data="DetailList"
               size="mini">
      </a-table>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import {pagingList} from '@/api/paging'
import {post} from '@/api/http'
import {useTable, useRowKey, useTableColumn, usePagination, useRowSelection} from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import {ref, reactive, onMounted, toRefs} from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import {Form, Message, Modal} from '@arco-design/web-vue'
import {FormInstance} from '@arco-design/web-vue/es/form'
import {baseURL} from '../../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import {AnyARecord} from 'dns'

import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'
import {localeText} from '@/api/aggridZw'

interface BrandInfo {
  id: any
  remark: string | undefined
  createName: string | undefined
  createTime: string | undefined
  updateName: string | undefined
  updateTime: string | undefined
  deleteState: any
  obsoleteState: any
  serial: any
  stepNo: any
  programNumber: any
  programType: any
  programName: any
  processingStep: any
  StepNameList: any[]
  programId: any
}

export default {
  name: 'DyeingProcessSteps',
  setup() {
    let selectedRowKeys1 = ref()
    let dataList: any = ref([])
    const total = ref(10)
    const page = ref(1)
    const size = ref(10)

    function PageSize(val: any) {
      pagination.page = val
      doRefresh()
    }

    function change1(val: any) {
      pagination.pageSize = val
      doRefresh()
    }

    const headerShow = ref<boolean>(true)

    //查询方法
    function doRefresh() {
      // updateGridState01()
      pageData.pageLoading = true
      post({
        url: '/pdm/dyeCraftStep/selectPage',
        data: {
          page: page.value,
          size: size.value,
          deleteState: '0',
          id: pageData.programId,
          programNumber: pageData.programNumber
        },
      })
          .then(({data, code}: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
    }

    const {selectedRowKeys, onSelectionChange} = useRowSelection()
    //成分表勾选返回的id
    const selectedRowKeysCf = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')

    const tableColumns = useTableColumn([
      {
        title: '序号',
        key: 'id',
        dataIndex: 'id',
        width: 150,
      },
      {
        title: '程序号',
        key: 'programNumber',
        dataIndex: 'programNumber',
        width: 150,
      },
      {
        title: '程序名称',
        key: 'programName',
        dataIndex: 'programName',
        width: 150,
      },
      {
        title: '程序类型',
        key: 'programType',
        dataIndex: 'programType',
        width: 150,
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
      },
      {
        title: '操作',
        key: 'id',
        slotName: 'act',
        width: 150,
        fixed: 'right',
      },
    ])

    const tableColumns1 = useTableColumn([
      {
        title: '步骤编号',
        key: 'stepNo',
        dataIndex: 'stepNo',
        width: 150,
        slotName: 'stepNo',
      },
      {
        title: '工艺步骤',
        key: 'processingStep',
        dataIndex: 'processingStep',
        width: 150,
        slotName: 'processingStep',
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
        slotName: 'remark',
      },
    ])

    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 105
        obj['cellRenderer'] = {
          template: `
            <a-space>
              <el-button style="color:#165dff;" link @click="a">修改</el-button>
              <el-button style="color:#165dff;" link @click="a2">详情</el-button>
            </a-space>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            const a2 = () => {
              Details(props.params.data)
            }
            return {
              a,
              a2,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)

    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      isLxs: boolean
      StepNameList: any[]
      cxNameList: any[]
      programName: any
      programType: any
      programId: any
      NumberList: any[]
      cxNumberList: any[]
      programNumber: any
      cxIdList: any[]
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增染色工艺步骤',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      isLxs: false,
      StepNameList: [],
      cxNameList: [],
      programName: '',
      programType: '',
      programId: null,
      NumberList: [],
      cxNumberList: [],
      programNumber: '',
      cxIdList: [],
    })

    interface gcType {
      id: any
      company: any
    }

    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({programNumber: '', deleteState: 0})
    }

    //下拉数据
    const options = ref<any>(pageData.cxNameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {programNumber: value, deleteState: 0}
        loading.value = true
        selCxAll(ob)
        options.value = pageData.cxNameList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: '/pdm/ProgramNumber/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.cxNameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      // 切换tap到本页面执行的方法
      emitter.on('DyeingProcessSteps', () => {
        doRefresh()
      })
      pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
      //弹出层的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight
      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight
        }
      })
    })

    //查询
    const selectHandler = () => {
      pagination.page = 1
      doRefresh()
    }
    const queryData = reactive({
      programNumber: '',
    })
    const addHandler = () => {
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else {
          dataForm[key] = ''
        }
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增染色工艺步骤'
    }
    const dataForm = reactive<BrandInfo>({
      id: null,
      remark: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      deleteState: 0,
      obsoleteState: '',
      serial: 0,
      stepNo: '',
      programNumber: '',
      programType: '',
      programName: '',
      processingStep: '',
      StepNameList: [],
      programId: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }
    //程序名称
    const wlmcFocus = () => {
      if (dataForm.programNumber == '') {
        return
      } else {
        post({
          url: '/pdm/dyeCraftStep/select',
          data: {
            programNumber: dataForm.programNumber,
          },
        }).then(({data, code}: any) => {
          if (code === 200) {
            pageData.cxNameList = data
          }
        })
      }
    }
    const wlChange = (val: any) => {
      pageData.cxNameList.forEach((item: any) => {
        if (item.programName == val) {
          dataForm.programNumber = item.programNumber
        }
      })
    }
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          formRef.value?.validate().then((err) => {
            if (!err) {
              pageData.pageLoading = true
              if (pageData.sideTitle === '新增染色工艺步骤') {
                post({
                  url: '/pdm/dyeCraftStep/insert',
                  data: {
                    programNumber: dataForm.programNumber,
                    programType: dataForm.programType,
                    programName: dataForm.programName,
                    list: dataList.value,
                  },
                })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        selectedRowKeys1.value = []
                        pageData.showAdd = false
                        Message.success({
                          content: '新增成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      doRefresh()
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
              } else {
                dataList.value.forEach((item: any) => {
                  delete item.isTypeIds
                })
                post({
                  url: '/pdm/dyeCraftStep/update',
                  data: {
                    programNumber: dataForm.programNumber,
                    programType: dataForm.programType,
                    programName: dataForm.programName,
                    id: dataForm.id,
                    list: dataList.value,
                  },
                })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        selectedRowKeys1.value = []
                        Message.success({
                          content: '修改成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      //doRefresh();
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
              }
            }
          })
        }
      })
    }
    const sideNo = () => {
      selectedRowKeys1.value = []
      dataList.value = []
      pageData.showAdd = false
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          post({
            url: '/pdm/dyeCraftStep/deleteList',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
              .then(({code, data}: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '修改失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
        },
      })
    }

    let craftStepIds = ''
    const editHandler = (record: BrandInfo) => {
      for (let key in record) {
        dataForm[key] = record[key]
      }
      craftStepIds = record.id
      //拿到此页面的详情
      post({
        url: '/pdm/DyeCraftStepSon/select',
        data: {
          craftStepId: record.id,
          deleteState: 0,
        },
      }).then(({data, code}: any) => {
        if (code === 200) {
          dataList.value = data
          dataList.value.forEach((item: any) => {
            item['isTypeIds'] = isTypeIds++
          })
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
      pageData.sideTitle = '修改染色工艺步骤'
      pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值只能是英文数字组合或英文，数字！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = (record: any) => {
      record.stepNo = record.stepNo.toUpperCase()
    }
    //导出
    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          idList.push(o['id'])
        })
        //将表头拼接出来
        let head =
            '<th>序号</th><th>步骤编号</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return (
              gridOption.value
                  .getSelectedRows()
                  .map((o: any) => {
                    return o.id
                  })
                  .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['id'] + '</td>'
          body += '<td>' + o['stepNo'] + '</td>'
          body += '<td>' + o['remark'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '染色工艺步骤定义', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
          .get(baseURL + '/pdm/dyeCraftStep/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '染色工艺步骤定义.xlsx')
            }
          })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
            .post(baseURL + '/pdm/dyeCraftStep/importModelData', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
      })
      inputEle.click()
    }
    //下拉框得到焦点
    const focusSel1 = () => {
      selCxAll1({technologyStep: ''})
    }

    //下拉数据
    const options1 = ref<any>(pageData.StepNameList)
    const loading1 = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = {technologyStep: value, deleteState: 0}
        loading1.value = true
        selCxAll1(ob)
        options1.value = pageData.StepNameList
        loading1.value = false
      } else {
        options1.value = []
      }
    }

    //下拉框查询
    function selCxAll1(val: any) {
      post({
        url: '/pdm/TechnologyStep/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.StepNameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    // //设置权限
    // // ['查询', '新增', '删除', '导出', '导入']
    // const permissionStore = usePermission()

    // if (permissionStore.hasPermisson('ppzl.cx')) {

    //     pageData.btnList.push("查询")
    // }
    // if (permissionStore.hasPermisson('ppzl.xz')) {
    //     pageData.btnList.push("新增")
    // }
    // if (permissionStore.hasPermisson('ppzl.sc')) {
    //     pageData.btnList.push("删除")
    // }
    // if (permissionStore.hasPermisson('ppzl.dc')) {
    //     pageData.btnList.push("导出")
    // }
    // if (permissionStore.hasPermisson('ppzl.dr')) {
    //     pageData.btnList.push("导入")
    // }
    // if (permissionStore.hasPermisson('ppzl.xg')) {
    //     pageData.isEdit = true
    // }
    // console.log(permissionStore.hasPermisson('ppzl.cx'));

    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      width: 190
    }
    const cxChange = (val: any) => {
      if (pageData.programNumber === '') {
        pageData.programName = ''
        pageData.programType = ''
      }
      post({
        url: '/pdm/ProgramNumber/select',
        data: {
          programNumber: pageData.programNumber,
        },
      }).then((res: any) => {
        if (res.code == 200) {
          if (pageData.programNumber) {
            pageData.programName = res.data[0].programName
            pageData.programType = res.data[0].programType
          }
        }
      })
    }
    const cxClick = () => {
      if (dataForm.programNumber == '') {
        Message.error('请先选择程序号！')
        return
      }
    }
    //下拉框得到焦点 新增里的程序号
    const focusSel5 = () => {
      selCxAll5({programNumber: '', deleteState: 0})
    }

    //下拉数据 新增里的程序号
    const options5 = ref<any>(pageData.NumberList)
    const loading5 = ref(false)
    const handleSearch5 = (value: any) => {
      if (value) {
        const ob = {programNumber: value, deleteState: 0}
        loading5.value = true
        selCxAll5(ob)
        options5.value = pageData.NumberList
        loading5.value = false
      } else {
        options5.value = []
      }
    }

    //下拉框查询 新增里的程序号
    function selCxAll5(val: any) {
      post({
        url: '/pdm/ProgramNumber/select',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.NumberList = data
        } else {
        }
      })
    }

    const numChange = (val: any) => {
      if (dataForm.programNumber == '') {
        dataForm.programType = ''
        dataForm.programName = ''
        return
      }
      let list = pageData.NumberList.filter(function (o: any) {
        return o['programNumber'] == val
      })
      dataForm.programName = list[0]['programName']
      dataForm.programType = list[0]['programType']
    }
    //程序号带出名称和类型
    const cxmcFocus2 = () => {
      if (
          dataForm.programNumber != '' &&
          dataForm.programNumber != null &&
          dataForm.programNumber != undefined
      ) {
        post({
          url: '/pdm/ProgramNumber/select',
          data: {
            programNumber: dataForm.programNumber,
          },
        }).then(({data, code}: any) => {
          if (code === 200) {
            pageData.cxNumberList = data
          }
        })
      }
    }
    //当程序号为空时，名称和类型也为空
    const cxChange2 = (val: any) => {
      if (dataForm.programNumber == '') {
        dataForm.programType = ''
        dataForm.programName = ''
        return
      } else {
        pageData.cxNumberList.forEach((item: any) => {
          if (item.programNumber == val) {
            dataForm.programType = item.programType
            dataForm.programName = item.programName
          }
        })
      }
    }
    const cxClick2 = () => {
      if (dataForm.programNumber == '') {
        Message.error('请先选择程序号！')
        return
      }
    }
    const pagingList1: any = ref(pagingList)
    const localeText1: any = ref(localeText)
    const huiche = () => {
      doRefresh()
    }

    let isTypeIds = 0
    const addSteps = () => {
      dataList.value.push({
        stepNo: '',
        processingStep: '',
        remark: '',
        isTypeIds: isTypeIds++,
      })
    }
    const delSteps = () => {
      if (selectedRowKeys1.value.length == 0) {
        Message.error('请选择要删除的数据')
        return
      }
      if (selectedRowKeys1.value.length > 1) {
        selectedRowKeys1.value.forEach((item: any, index: any) => {
          dataList.value.forEach((items: any, indexs: any) => {
            if (item == items.isTypeIds) {
              dataList.value.splice(indexs, 1)
            }
          })
        })
        if (selectedRowKeys1.value.length > dataList.value.length) {
          selectedRowKeys1.value = []
        }
      } else {
        dataList.value.some((item: any, index: any) => {
          if (selectedRowKeys1.value == item.isTypeIds) {
            dataList.value.splice(index, 1)
            selectedRowKeys1.value = []
          }
        })
      }
    }
    let DetailList: any = ref([])
    const visible1 = ref(false)
    const Details = (record: any) => {
      //拿到此页面的详情
      post({
        url: '/pdm/DyeCraftStepSon/select',
        data: {
          craftStepId: record.id,
          deleteState: 0,
        },
      }).then(({data, code}: any) => {
        if (code === 200) {
          DetailList.value = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
      visible1.value = true
    }

    //下拉框得到焦点 程序号
    const focusSel2 = () => {
      selCxAll2({"programNumber": "", deleteState: 0});
    }

    //下拉数据 程序号
    const options2 = ref<any>(pageData.cxIdList);
    const loading2 = ref(false);
    const handleSearch2 = (value: any) => {
      if (value) {
        const ob = {programNumber: value, deleteState: 0}
        loading2.value = true;
        selCxAll2(ob);
        options2.value = pageData.cxIdList;
        loading2.value = false;
      } else {
        options2.value = []
      }
    };

    //下拉框查询 程序号
    function selCxAll2(val: any) {
      post({
        url: "pdm/dyeCraftStep/selectProgramNumber",
        data: val
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.cxIdList = data.list;
        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }

    let program = ''
    const copyCode = () => {
      program = dataForm.programId
      dataForm.programId = dataForm.programId.split('——')[0]
    }

    //复制
    const visible = ref(false);

    function copyPro() {
      visible.value = true
      dataForm.programId = ''
    }

    function handleSave() {
      let ids: any = pageData.cxIdList.find((o: any) => o.programName === program)
      post({
        url: "pdm/DyeCraftStepSon/select",
        data: {
          craftStepId: ids.id,
          deleteState: 0,
        }
      }).then(({data, code, message}: any) => {
        if (code === 200) {
          let newData: any = []
          dataList.value = []
          data.forEach((o: any) => {
            var obj = {processingStep: o.processingStep, remark: o.remark, craftStepId: craftStepIds, isTypeIds: isTypeIds++}
            newData.push(obj)
          })
          dataList.value = newData
          visible.value = false
        } else {
          Message.error({
            content: message,
            duration: 5000,
          });
        }
      });
    }

    const {saveGridState: saveGridState01, updateGridState: updateGridState01} = saveOrUpdateGridState01('DyeingProcessSteps01', gridOption, colState, tc)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    return {
      visible,
      copyCode,
      copyPro,
      handleSave,
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      colState,
      visible1,
      DetailList,
      Details,
      addSteps,
      delSteps,
      tableColumns1,
      selectedRowKeys1,
      dataList,
      pagingList1,
      huiche,
      localeText1,
      cxmcFocus2,
      cxClick2,
      cxChange2,
      numChange,
      focusSel5,
      options5,
      loading5,
      handleSearch5,
      cxClick,
      cxChange,
      editHandler,
      deleteHandler,
      sideOk,
      sideNo,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      isChiese,
      inputBlur,
      exports,
      options,
      loading,
      handleSearch,
      focusSel,
      downloadHandler,
      importHandler,
      options1,
      options2,
      loading1,
      loading2,
      handleSearch1,
      handleSearch2,
      focusSel1,
      focusSel2,
      headerShow,
      handleChange,
      PageSize,
      change1,
      defaultColDef,
      tc,
      gridOption,
      gridReady,
      total,
      page,
      size,
      wlmcFocus,
      wlChange,
    }
  },
  components: {Toolbar, PageTabelLayout, },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>